from datetime import timedelta
import base64
import aiohttp
from fastapi import HTTPException
import io
from core.logger import log


async def put_image(complete_binary,image_id,minio_client):
    try:
        minio_client.put_object("images", f"{str(image_id)}.png", io.BytesIO(complete_binary), length=len(complete_binary), content_type="image/png")
        url = minio_client.presigned_get_object("images", f"{str(image_id)}.png", expires=timedelta(days=7))
        return  url
    except Exception as e:
        log.info(f"minio_util中put_image函数报错了:{e}")
        return None

async def get_image_by_prefix(prefix:str,minio_client):
    try:
        objects = minio_client.list_objects("images",prefix=prefix,recursive=True)
        urls = []
        for obj in objects:
            url = minio_client.presigned_get_object("images",object_name=obj.get_object_name(),expires=timedelta(days=1))
            urls.append(url)
        return urls
    except Exception as e:
        log.info(f"minio_util中get_image_by_prefix函数报错了:{e}")
        return None



async def url_to_base64_async(image_url: str) -> str:
    """
    异步将图片URL转换为Base64编码
    """
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(image_url) as response:
                response.raise_for_status()
                image_data = await response.read()
                image_base64 = base64.b64encode(image_data).decode('utf-8')
                return image_base64
    except Exception as e:
        log.exception(f"图片URL转Base64失败: {e}")
        raise HTTPException(status_code=500, detail="图片转换失败")
